package com.bitin.common.data.model;

import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import org.springframework.util.Assert;

import java.util.regex.Pattern;

/**
 * A value object abstraction of an phone number.
 *
 * @Author: Mr.Lu
 * @Datetime 2024/8/13 21:53
 */
@Embeddable
public class Phone {
    private static final String PHONE_REGEX = "^1[3456789]\\d{9}$";
    private static final Pattern PATTERN = Pattern.compile(PHONE_REGEX);

    @Column(name = "phone", unique = true, nullable = false, length = 11)
    private String value;

    /**
     * Creates a new {@link Phone} from the given string source.
     *
     * @param phone must not be {@literal null} or empty.
     */
    public Phone(String phone) {
        Assert.isTrue(isValid(phone), "Invalid phone number!");
        this.value = phone;
    }

    protected Phone() {

    }

    /**
     * Returns whether the given {@link String} is a valid {@link Phone} which means you can safely instantiate the
     * class.
     *
     * @param candidate
     * @return
     */
    public static boolean isValid(String candidate) {
        return candidate == null ? false : PATTERN.matcher(candidate).matches();
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return value;
    }
}
